package org.jeecg.config;


import com.alibaba.druid.sql.SQLUtils;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.visitor.SchemaStatVisitor;
import com.alibaba.druid.stat.TableStat;
import com.alibaba.druid.util.JdbcUtils;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Component
public class ParserHelpers {

    static DynamicDataSourceProperties dynamicDataSourceProperties;
    @Autowired
    public ParserHelpers(DynamicDataSourceProperties dynamicDataSourceProperties1){
        ParserHelpers.dynamicDataSourceProperties=dynamicDataSourceProperties1;
    }


    /**
     * 从SQL中提取表名(sql中出现的所有表)
     * @param sql sql语句
     * @return List<String>
     */
    public static List<String> getTablesBydruid(String sql){
        String url = dynamicDataSourceProperties.getDatasource().get(dynamicDataSourceProperties.getPrimary()).getUrl();
        String dbType = JdbcUtils.getDbType(url, null);
        List<String> result = new ArrayList<String>();
        List<SQLStatement> stmtList = SQLUtils.parseStatements(sql, dbType);
        for(SQLStatement stmt:stmtList){
//也可以用更精确的解析器，如MySqlSchemaStatVisitor
            SchemaStatVisitor visitor = new SchemaStatVisitor();
            stmt.accept(visitor);
            Map<TableStat.Name, TableStat> tables = visitor.getTables();
            for(TableStat.Name name: tables.keySet()){
                result.add(name.getName());
            }
        }
        return result;
    }
}
